package com.woohua.thread.cyclicbarrier;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

/***
 * @title MakeTir
 * @description
 * @author woo hua
 * @version 1.0.0
 * @create 2023/3/17 14:42
 **/
public class MakeTire implements Runnable {

    private CyclicBarrier cyclicBarrier;

    public MakeTire(CyclicBarrier cyclicBarrier) {
        this.cyclicBarrier = cyclicBarrier;
    }

    @Override
    public void run() {
        exec();
    }

    /**
     * 模板模拟制造轮胎
     */
    private void exec() {
        // 造完后继续造下一个
        while (true) {
            try {
                System.out.println("Start making tire...");
                long millis = ((int) (1 + Math.random() * (5 - 1 + 1))) * 1000;
                TimeUnit.MILLISECONDS.sleep(millis);
                System.out.println("Making tire is finished.");

                // 等待其他部件造完
                cyclicBarrier.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }
}
